#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>

void sig2(int sig)
{
    std::cout << "receive signal: " << sig << " pid: " << getpid() << std::endl;
}

void sig2_define()
{
    signal(2, sig2);
    int p = 0;
    while (1)
    {
        std::cout << "run num: " << p++ << std::endl;
        sleep(1);
    }
}

void sig14(int sig);

void sig_alarm_sleep()
{
    signal(14, sig14);
    alarm(3);
    int p = 0;
    while (1)
    {
        std::cout << "run num: " << p++ << std::endl;
        sleep(1);
    }
}

void handlerSig(int sig)
{
    std::cout << "receive signal: " << sig << " pid: " << getpid() << std::endl;
}

void printallsig()
{
    for (int i = 1; i <= 31; i++)
    {
        signal(i, handlerSig);
    }
}

#include <functional>
#include <vector>
using funcp = std::function<void()>;

void print0()
{
    std::cout << "func: 0" << std::endl;
}

void print1()
{
    std::cout << "func: 1" << std::endl;
}

void print2()
{
    std::cout << "func: 2" << std::endl;
}

void print3()
{
    std::cout << "func: 3" << std::endl;
}

void sig14(int sig)
{
    std::cout << "receive signal: " << sig << " pid: " << getpid() << std::endl;
    alarm(1);
}
int main()
{
    // 信号2行为重定义
    // sig2_define();

    // 修改所有信号
    // printallsig();
    // alarm(1);
    // kill(getpid(), 22);
    // raise(23);

    // 唤醒和休眠程序
    // sig_alarm_sleep();
    std::vector<funcp> vecfun;
    vecfun.emplace_back(print0);
    vecfun.emplace_back(print1);
    vecfun.emplace_back(print2);
    vecfun.emplace_back(print3);

    signal(14, sig14);
    alarm(1);
    int p = 0;

    while (1)
    {
        vecfun[p]();
        p++;
        if (p >= 4)
            p = 0;
        pause();
        std::cout << "醒来" << std::endl;
    }

    return 0;
}
